

layui.use(['layer','element','form','upload'], function() {
    var	$ = layui.jquery,
        element = layui.element,
        form = layui.form,
        upload = layui.upload;


    // $(".block_type1").find('form').find('input').attr('disabled',true);
    // form.render();
    // tab 切换
    $(".tab_type1").on('click',function () {
        $(this).removeClass('layui-btn-primary');
        $('.tab_type2').addClass('layui-btn-primary');
        $(".block_type1").show();
        $(".block_type2").hide();
        $("input[name=keywordsType]").val(1);
    });
    $(".tab_type2").on('click',function () {
        $(this).removeClass('layui-btn-primary');
        $('.tab_type1').addClass('layui-btn-primary');

        $(".block_type2").show();
        $(".block_type1").hide();
        $("input[name=keywordsType]").val(2);

        if($("#type2-list").children().length==0) {
            // $("#baseimage-list").find('li').first().trigger('click');
            $.post('/index.php?route=Equip/getEquipByBase&iActId=1001',[],function (html) {
                renderType2Html(html);
            })
        }

    });

    var keywordsType = $("input[name=keywordsType]").val();
    if (keywordsType && keywordsType !='') {
        if (keywordsType == 1) {
            $(".tab_type1").trigger('click');
        } else if (keywordsType == 2) {
            $(".tab_type2").trigger('click');
        }
    }
    // 搜索
    $(".search-block2-btn").click(function () {
        var keywords = $(this).parent('.layui-inline').find('.layui-input').val();
        var equipId = $("input[name=equipId]").val();
        $.post('/index.php?route=Equip/getEquipByBase&iActId=1001',{keywords:keywords,equipId:equipId},function (html) {
            var that = $("#baseimage-list").children('li:eq(0)');
            $(that).siblings().removeClass('active');
            $(that).addClass('active');
            renderType2Html(html);
        })
    });


    //合成道具tab点击
    
    $("#baseimage-list").on('click','li',function () {
        var that = this;
        var equipId = $(this).data('equipid');
        $("input[name=equipId]").val(equipId);
        var data = {equipId:equipId};

        $.post('/index.php?route=Equip/getEquipByBase&iActId=1001',data,function (html) {
            $(that).siblings().removeClass('active');
            $(that).addClass('active');
            renderType2Html(html);
        })
    });
    function renderType2Html(html){

        $('#type2-list').html(html);
        // $('#type2-list').find('form').find('input').attr('disabled',true);


        //英雄
        var boxes = $('#type2-list').find('form');
        // $.each(boxes,function(i,box){
        //     var heros_type2 = $(box).find("[name='heroIds']").val();
        //
        //     var heroIds_type2 = heros_type2 ? heros_type2.split(',') :[];
        //     heroIds_type2.forEach(function (key) {
        //         $(box).find('.hero-list').append('<a class="item_'+key+'">||'+CONF.Heros[key]+'</a>');
        //     })
        //
        // });
        //配方

        $.each(boxes,function(i,box){
            var formula = $(box).find("[name='formula']").val();

            var formula_type2 = formula ? formula.split(',') :[];
            formula_type2.forEach(function (key) {
                $(box).find('.formula-list').append('<a class="item_'+key+'">||'+CONF.Equips[key]+'</a>');
            })

        });

        form.render();
    }

    //删除
    $(".block_type1").on('click','.action-to-delete',function () {

        var box = $(this).parents('form');
        layer.confirm('是否要删除该数据？', {icon: 3, title:'提示'}, function(index){
            var dataType = 5;
            var id = box.find("input[name=equipId]").val()
            layer.close(index);
            var url = "/index.php?route=Main/deleteData&iActId=1001";
            $.ajax({
                url: url, type: "post", dataType: "json",
                data: { dataType:dataType,id:id},
                beforeSend:function () {
                    this.layerIndex = layer.load(0, { shade: [0.5, '#393D49'] });
                },
                success:function(data){
                    if(data.status =="error"){
                        layer.msg(data.msg);//失败的表情
                        return;
                    }else if(data.status == "success"){
                        layer.msg(data.msg, {
                            icon: 1,//成功的表情
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                            parent.parent.$(".refresh").click();
                        });
                    }
                },
                complete: function () {
                    layer.close(this.layerIndex);
                },
            });
        });
    });

    $(".block_type2").on('click','.action-to-delete',function () {
        var box = $(this).parents('form');
        layer.confirm('是否要删除该数据？', {icon: 3, title:'提示'}, function(index){
            var dataType = 5;
            var id = box.find("input[name=equipId]").val()
            layer.close(index);
            var url = "/index.php?route=Main/deleteData&iActId=1001";
            $.ajax({
                url: url, type: "post", dataType: "json",
                data: { dataType:dataType,id:id},
                beforeSend:function () {
                    this.layerIndex = layer.load(0, { shade: [0.5, '#393D49'] });
                },
                success:function(data){
                    if(data.status =="error"){
                        layer.msg(data.msg);//失败的表情
                        return;
                    }else if(data.status == "success"){
                        layer.msg(data.msg, {
                            icon: 1,//成功的表情
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                            parent.parent.$(".refresh").click();
                        });
                    }
                },
                complete: function () {
                    layer.close(this.layerIndex);
                },
            });
        });
    });

    //基础道具编辑按钮
    /*$(".block_type1").on('click','.action-to-update',function () {

        var box = $(this).parents('form');
        box.find('input').removeAttr('disabled');
        box.find("[name='is_update']").val(1);
        box.find('.action-to-update').hide();
        box.find('.action-to-submit').show();

        form.render();

    });*/
    //合成道具编辑按钮
   /* $(".block_type2").on('click','.action-to-update',function () {
        var box = $(this).parents('form');
        box.find('input').removeAttr('disabled');
        box.find("[name='is_update']").val(1);
        box.find('.action-to-update').hide();
        box.find('.action-to-submit').show();

        form.render();
    });*/



    //基础道具点击保存
    $(".block_type1").on('click','.action-to-submit',function () {
        var index = layer.load(1);
        var box = $(this).parents('form');
        if (checkFormData(1,box)) {
            var data = box.serialize();

            $.post('/index.php?route=Equip/update&iActId=1001', data, function (res) {
                layer.close(index);
                if (res.status == "error") {
                    layer.msg(res.msg);//失败的表情
                    return;
                } else {
                    /*box.find('input').attr('disabled', true);

                    box.find('.action-to-update').show();
                    box.find('.action-to-submit').hide();
                    box.find("[name='is_update']").val(0);*/
                    form.render();
                    layer.msg('编辑成功');
                }
            });
        }
    });
    $(".block_type2").on('click','.action-to-submit',function () {

            var box = $(this).parents('form');
        var index = layer.load(1);
        if (checkFormData(2,box)) {
            var data = box.serialize();

            $.post('/index.php?route=Equip/update&iActId=1001', data, function (res) {
                layer.close(index);
                if (res.status == "error") {
                    layer.msg(res.msg);//失败的表情
                    return;
                } else {
                    /*box.find('input').attr('disabled', true);

                    box.find('.action-to-update').show();
                    box.find('.action-to-submit').hide();
                    box.find("[name='is_update']").val(0);*/
                    form.render();
                    layer.msg('编辑成功');
                }
            });
        }
    });



    //点击选择英雄时候的form
    var FROMBOX;
    //基础道具选择英雄
    // $(".block_type1").on('click','.select-hero',function () {
    //
    //     var box = $(this).parents('form');
    //     FROMBOX = box;
    //     var is_update = box.find("[name='is_update']").val();
    //     if(is_update==0) {
    //         return false;
    //     }
    //     var checkbox = ''
    //     var herosValue = box.find("[name='heroIds']").val();
    //     var heroIds = herosValue ? herosValue.split(','):[];
    //     $.each(CONF.Heros,function (key,name) {
    //         //选中
    //         var checked = '';
    //         if($.inArray(key,heroIds)!=-1){
    //             checked = 'checked';
    //         }
    //         checkbox +=  '<input '+checked+' type="checkbox" name="hero[]" value="'+key+'" title="'+name+'"  >';
    //     })
    //
    //     layer.open({
    //         type: 1,
    //         content: '<form id="hero-list" class="layui-form">' +checkbox+'</form>',
    //         btn:['确定'],
    //         offset: 't'
    //     })
    //     form.render('checkbox');
    // })
    //
    // //合成道具选择英雄
    // $(".block_type2").on('click','.select-hero',function () {
    //
    //     var box = $(this).parents('form');
    //     FROMBOX = box;
    //     var is_update = box.find("[name='is_update']").val();
    //     if(is_update==0) {
    //         return false;
    //     }
    //     var checkbox = ''
    //     var herosValue = box.find("[name='heroIds']").val();
    //     var heroIds = herosValue ? herosValue.split(','):[];
    //     $.each(CONF.Heros,function (key,name) {
    //         //选中
    //         var checked = '';
    //         if($.inArray(key,heroIds)!=-1){
    //             checked = 'checked';
    //         }
    //         checkbox +=  '<input '+checked+' type="checkbox" name="hero[]" value="'+key+'" title="'+name+'"  >';
    //     })
    //
    //     layer.open({
    //         type: 1,
    //         content: '<form id="hero-list" class="layui-form">' +checkbox+'</form>',
    //         btn:['确定'],
    //         offset: 't'
    //     })
    //     form.render('checkbox');
    // })

    //合成道具选择配方
    $(".block_type2").on('click','.select-formula',function () {
        var box = $(this).parents('form');
        FROMBOX = box;
        var is_update = box.find("[name='is_update']").val();
        if(is_update==0) {
            return false;
        }
        var checkbox = ''
        var formulaValue = box.find("[name='formula']").val();
        var formulas = formulaValue ? formulaValue.split(','):[];
        $.each(CONF.Equips,function (key,name) {
            //选中
            var checked = '';
            var readonly = '';
            var count = 0;
            if($.inArray(key,formulas)!=-1){
                checked = 'checked';
                readonly = 'readonly'
            }
            for (i = 0; i < formulas.length; i++) {
                if (formulas[i] == key) {
                    count++;

                }
            }
            count = count > 0 ? count : 1;

            checkbox +=  '<input '+checked+' type="checkbox" name="formula[]" value="'+key+'" title="'+name+'">';
            checkbox +=  '<input '+readonly+' type="number" name="'+key+'" value="'+count+'" style="width: 50px;"><br/>';

        })

        layer.open({
            type: 1,
            content: '<form id="formulas-list" class="layui-form">' +checkbox+'</form>',
            btn:['确定'],
            offset: 't'
        })
        form.render('checkbox');
    })

    function renderHero(key,is) {
        var box = FROMBOX;

        var herosValue = box.find("[name='heroIds']").val();
        var heroIds = herosValue ? herosValue.split(','):[];
        //添加
        if(is){
            if($.inArray(key,heroIds) !=-1) {
                return;
            }
            heroIds.push(key);

            box.find(".hero-list").append('<a class="item_'+key+'">||'+CONF.Heros[key]+'</a>');
        } else {
            //删除
            var pos = $.inArray(key,heroIds);
            if(pos !=-1){
                heroIds.splice(pos,1);

            }
            box.find(".hero-list").find(".item_"+key).remove();
        }
        box.find("[name='heroIds']").val(heroIds.join(','));
    }

    function renderFormula(key,is){
        var box = FROMBOX;
        var formulaValue = box.find("[name='formula']").val();
        var formulaIds = formulaValue ? formulaValue.split(','):[];
        var formulas_key = $("#formulas-list").find("[name="+key+"]");
        console.log('formulas_key',formulas_key.val());

        //添加
        if(is){
            if($.inArray(key,formulaIds) !=-1) {
                return;
            }

            formulas_key.attr('readonly','readonly');
            var count = formulas_key.val();
            if (count > 0) {
                for (i = 0; i < count; i++) {
                    formulaIds.push(key);
                    box.find(".formula-list").append('<a class="item_'+key+'">||'+CONF.Equips[key]+'</a>');
                }

            }
        } else {
            formulas_key.attr('readonly',false);
            //删除
            var pos = $.inArray(key,formulaIds);
            if(pos !=-1){
                formulaIds.splice(pos,1);
            }
            box.find(".formula-list").find(".item_"+key).remove();
        }
        box.find("[name='formula']").val(formulaIds.join(','));
    }
    form.on('checkbox', function(data){
        var name = $(data.elem).attr('name');
        var is = data.elem.checked;
        var value = data.value;
        if(name=='hero[]') {
            renderHero(value,is);
        } else {
            renderFormula(value,is);
        }


    });


   /* $(".block_type1").find('form').find('input').attr('disabled',true);
    form.render();*/

    //更换图标
    $(".block_type1").on("mousedown",".action-update-image",function () {
        var box = $(this).parents('form');
        var is_update = box.find("[name='is_update']").val();
        var equipId = box.find("[name='equipId']").val();
        if(is_update==0) {
            return false;
        }
        upload.render({
            elem: '.update-image_'+equipId //绑定元素
            ,url:'/index.php?route=LolApi/uploadImg&iActId=1001' //上传接口
            , accept: 'images'
            ,data:{
                id:1,
                type:'equip'
            }
            ,done: function(res){

                box.find("[name='imagePath']").val(res.imagePath);
                box.find('img').attr('src',res.imagePath);
                //上传完毕回调
            }
            ,error: function(){
                //请求异常回调
            }
        });
    })

    $(".block_type2").on("mousedown",".action-update-image",function () {
        var box = $(this).parents('form');
        var is_update = box.find("[name='is_update']").val();
        var equipId = box.find("[name='equipId']").val();
        if(is_update==0) {
            return false;
        }
        upload.render({
            elem: '.update-image_'+equipId //绑定元素
            ,url:'/index.php?route=LolApi/uploadImg&iActId=1001' //上传接口
            , accept: 'images'
            ,data:{
                id:1,
                type:'equip'
            }
            ,done: function(res){

                box.find("[name='imagePath']").val(res.imagePath);
                box.find('img').attr('src',res.imagePath);
                //上传完毕回调
            }
            ,error: function(){
                //请求异常回调
            }
        });
    })

    // 添加
    $(".equip-add").on('click', function(){
        layer.open({
            title: '添加道具',
            type: 2,
            area:['512px','550px'],
            content: '/index.php?route=Equip/add&iActId=1001'
        });
    });

    $(".equip-type-two").hide();
    form.on('select(type)', function(data){
        var val = data.value;
        if (val == 1) {
            $(".equip-type-two").hide();
        }
        if (val == 2) {
            $(".equip-type-two").show();
        }
    });

    form.on('submit(add-equip-filter)', function(data){
        if (checkFormData($('select[name=type]').val(),$(".add-equip-form"))) {
            $.ajax({
                url: "/index.php?route=Equip/addSave&iActId=1001",
                type: 'POST',
                dataType: 'JSON',
                data: $(".add-equip-form").serializeArray(),
                success: function (res) {
                    if (res.status == 'success') {
                        window.parent.location.reload();//刷新父页面
                        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                        parent.layer.close(index);
                    } else {
                        layer.msg(res.msg);
                        return false;
                    }
                }
            });
        }
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });


    upload.render({
        elem: "#addEquipImg"//绑定元素
        ,url:'/index.php?route=LolApi/uploadImg&iActId=1001' //上传接口
        , accept: 'images'
        ,data:{
            id:1,
            type:'equip'
        }
        ,done: function(res){

            $(".add-equip-form").find("[name='imagePath']").val(res.imagePath);
            $("#add-image-path").attr('src',res.imagePath);
            //上传完毕回调
        }
        ,error: function(){
            //请求异常回调
        }
    });

    function checkFormData(type,form) {
        var equipId = form.find("input[name=equipId]").val();
        if (isNaN(equipId) || equipId == '') {
            layer.msg('道具ID必须为数字类型');
            return false;
        }
        var name = form.find("input[name=name]").val();
        if (name == '') {
            layer.msg('道具名称不能为空');
            return false;
        }
        var effect = form.find("input[name=effect]").val();
        if (effect == '') {
            layer.msg('道具效果不能为空');
            return false;
        }
        var keywords = form.find("input[name=keywords]").val();
        if (keywords == '') {
            layer.msg('关键词不能为空');
            return false;
        }
        var imagePath = form.find("input[name=imagePath]").val();
        if (imagePath == '') {
            layer.msg('请上传图标');
            return false;
        }
        if (type == 2) {
            var formula = form.find("input[name=formula]").val();
            if (formula == '') {
                layer.msg('请选择合成道具');
                return false;
            }
        }
        return true;
    }



})





